############################################
# Copyright (c) 2018 
#
# Written by 
############################################
import sys
import os

sys.path.append(".")

from common.define import *
from UniformPrinter import *
from lib.log import *
from lib.iniParser import *

def covert_papersize(papersize):
	ps_t = {'A3' : '8',
                'A4'   : '9',
                'A4S' : '10',
                'A5'   : '11',
                'B4'   :  '12',
                'B5'   :  '13'}
	if papersize in ps_t:
		papersize = ps_t[papersize]
	return papersize
	
def main(currentPath, argv):
	# we don't use argument in this version
	iniPath = currentPath+"\setup.ini"
	ini = IniParser(iniPath)
	
	# DEBUG_LEVEL
	level = ini.parserGet("set", "level")
	logPath = currentPath+"\pp.log"
	pplog.enable_log(logPath)
	pplog.set_log_level(level)
	
	# Dump setup.ini
	pp_debug("############# Dump Setup.ini Start #############")
	ini.iniDump()
	pp_debug("############# Dump Setup.ini End #############")
	
	# for performence, we will check the file exist or not firstly
	if os.path.exists(ini.parserGet("set", "app"))  == False:
		pp_error("app %s  is not exist!" %(ini.parserGet("set", "app")))
		return
	if os.path.exists(ini.parserGet("set", "file"))  == False:
		pp_error("file %s  is not exist!" %(ini.parserGet("set", "file")))
		return

	po = PrinterOperation()
	ret = po.OpenPrinter()
	if (ret == RET_NG):
		pp_error("Critical Error!")
		ini.parserSet("get", "result", RET_NG)
		return
	pp_info("Open Printer Succeed")
	
	attributes = po.getPrinterAttributes(2)  # level 2 is PRINTER_INFO_2
	status = po.getPrinterStatus(attributes)
	if (status != 0):
		pp_error("Pinter Status %s Abnormal!" %(status))
		po.closePrinter()
		ini.parserSet("get", "result", RET_NG)
		return
	pp_info("Printer Status Corrcet")
	
	# set duplex
	duplex = ini.parserGet("set", "duplex")
	po.setDuplex(attributes, duplex)
	# set color
	color = ini.parserGet("set", "color")
	po.setColor(attributes, color)
	# set copies
	copies = ini.parserGet("set", "copies")
	po.setCopies(attributes, copies)
	# set pagesize
	papersize = ini.parserGet("set", "papersize")
	papersize = covert_papersize(papersize)
	po.setPaperSize(attributes, papersize)
	pp_info("Attributes Set Succeed")

	# starat print
	totalpages = 0
	pp_info("Start Print Processes")
	f = FileOperation(ini.parserGet("set", "app"), ini.parserGet("set", "file"))
	f.sartPrint()
	totalpages = int(f.getPages()) * int(copies)
	pp_info("End Print Processes")
	ini.parserSet("get", "result", 0)
	ini.parserSet("get", "totalpages", totalpages)

	# close pointer
	po.closePrinter()
	pp_info("Colse Printer Succeed")

if __name__ == "__main__":
	path = os.path.split(os.path.abspath(sys.argv[0]))[0]
	main(path, sys.argv[1:])
	exit()